package com.cmwa.scbp.sys.permission.privilege.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.cmwa.scbp.base.constants.Constant;
import com.cmwa.scbp.base.mvc.entity.Employee;
import com.cmwa.scbp.base.mvc.entity.Page;
import com.cmwa.scbp.base.mvc.entity.SearchParam;
import com.cmwa.scbp.sys.permission.authorityGroup.dao.AuthorityGroupDao;
import com.cmwa.scbp.sys.permission.dataRole.dao.RoleDao;
import com.cmwa.scbp.sys.permission.dataRole.dao.RoleResourceRelationsDao;
import com.cmwa.scbp.sys.permission.dataRole.entity.RoleResourceVo;
import com.cmwa.scbp.sys.permission.privilege.dao.PrivilegeDao;
import com.cmwa.scbp.sys.permission.privilege.entity.PrivilegeVo;
import com.cmwa.scbp.sys.permission.privilege.service.PrivilegeService;
import com.cmwa.scbp.utils.SessionUtils;

/**
 * 权限控制service
 * 
 * @author zhougz
 * @date 2016年03月31日
 * 
 */
@Service("privilegeService")
public class PrivilegeServiceImpl implements PrivilegeService {

	private static Logger logger = LoggerFactory.getLogger(PrivilegeServiceImpl.class);
	@Resource
	private PrivilegeDao privilegeDao;
	@Resource
	private RoleDao roleDao;
	@Resource
	private RoleResourceRelationsDao roleResourceRelationsDao;// 角色资源关系
	@Resource
	private AuthorityGroupDao authorityGroupDao;// 分享权限组表
	@Resource(name = "scbpSqlSessionTemplate")
	private SqlSessionTemplate scbpSqlSessionTemplate;

	/**
	 * 
	 */
	@Override
	public void executeUpdateLimit() {
		if (logger.isDebugEnabled()) {
			logger.debug("更新开始");
		}
		privilegeDao.deleteResourceLimit(null, null);
		privilegeDao.insertResourceLimit(null, null);
	}

	/**
	 * 分页查询角色权限信息
	 * 
	 * @author ex-huangch 2016.5.24
	 * @return
	 */
	@Override
	public Page<PrivilegeVo> privilegeListPage(SearchParam param) {
		List<PrivilegeVo> items;
		String empId = (String) param.getSp().get("empId");
		if (StringUtils.isEmpty(empId)) {
			items = privilegeDao.privilegeListPageWithoutEmpId(param);
		} else {
			items = privilegeDao.privilegeListPage(param);
		}

		return Page.create(items, param.getStart(), param.getLimit(), param.getTotal());
	}

	/**
	 * 根据角色ID查询当前角色 相应类型下 的可选资源列表
	 */
	public Page<PrivilegeVo> queryResourceForSel(SearchParam param) {

		String roleId = (String) param.getSp().get("roleId");
		String type = privilegeDao.queryRoleTypeByRoleId(roleId);
		List<PrivilegeVo> privilegeVos = null;
		if ("1".equals(type)) {
			privilegeVos = privilegeDao.queryResourceForSelByTypeOneListPage(param);
		} else {
			privilegeVos = new ArrayList<PrivilegeVo>();
		}

		return Page.create(privilegeVos, param.getStart(), param.getLimit(), param.getTotal());
	}

	/**
	 * TYPE取值含义 1 数据角色-系列产品
	 */
	@Override
	public Page<PrivilegeVo> querySelectedResourceListPage(SearchParam param) {
		String roleId = (String) param.getSp().get("roleId");
		String type = privilegeDao.queryRoleTypeByRoleId(roleId);

		List<PrivilegeVo> privilegeVos = new ArrayList<PrivilegeVo>();
		if ("1".equals(type)) {
			privilegeVos = privilegeDao.queryResourceInfoByTypeOneListPage(param);
		} else {
			privilegeVos = new ArrayList<PrivilegeVo>();
		}
		return Page.create(privilegeVos, param.getStart(), param.getLimit(), param.getTotal());
	}

	@Override
	public void removeResource(String roleId, String isAll, String resIds) {
		SqlSession sqlSession = null;
		try {
			// 获取批处理SqlSession
			sqlSession = scbpSqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
			String type = privilegeDao.queryRoleTypeByRoleId(roleId);

			if (!StringUtils.isEmpty(type)) {
				// 如果是全量
				if (Constant.YES.equals(isAll)) {
					// 删除所有的角色系列产品关系表数据
					roleResourceRelationsDao.deleteRoleResourceRelations(roleId, null, type);
				} else {
					// 按指定资源删除关联关系
					if (StringUtils.isNotEmpty(resIds)) {
						String[] resIdsArray = resIds.split(",");
						List<String> resIdList = Arrays.asList(resIdsArray);
						int stepSize = 500;
						int total = resIdList.size();
						int step = (total + stepSize - 1) / stepSize;
						List<String> subList = null;
						for (int i = 0; i < step; i++) {
							if (i == step - 1) {
								subList = resIdList.subList(i * stepSize, total);
							} else {
								subList = resIdList.subList(i * stepSize, (i + 1) * stepSize);
							}
							// 删除角色资源关系表数据
							roleResourceRelationsDao.deleteRoleResourceRelations(roleId, subList, type);
						}
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("数据权限设置添加权限异常", e);
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
	}

	@Override
	public void addResource(String roleId, String isAll, String resIds) {

		SqlSession sqlSession = null;
		try {
			// 获取批处理SqlSession
			sqlSession = scbpSqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);

			Employee employee = SessionUtils.getEmployee();
			// 接受前台传过来的值
			String type = privilegeDao.queryRoleTypeByRoleId(roleId);
			// 根据条件查询分享角色ID集合
			List<String> shareIds = authorityGroupDao.getShareIds(type, roleId);
			shareIds.add(roleId);

			if (!StringUtils.isEmpty(type)) {
				// 如果是全量
				if (Constant.YES.equals(isAll)) {
					if ("1".equals(type)) {
						// 系列产品
						roleResourceRelationsDao.addAllResourceToRoles(shareIds, employee.getID(), type);
					}
				} else {
					int counter = 0;
					if (StringUtils.isNotEmpty(resIds)) {
						String[] resIdsArray = resIds.split(",");
						for (int i = 0; i < resIdsArray.length; i++) {
							for (int n = 0; n < shareIds.size(); n++) {
								if ("1".equals(type)) {
									// 系列产品
									RoleResourceVo rprvo = new RoleResourceVo();
									rprvo.setRoleId(shareIds.get(n));
									rprvo.setResourceId(resIdsArray[i]);
									rprvo.setResourceType("1");
									rprvo.setCreateId(employee.getID());
									sqlSession.insert(
											"com.cmwa.scbp.sys.permission.dataRole.dao.RoleResourceRelationsDao.saveResourceToRoles",
											rprvo);
								}
								counter++;
								if (counter >= 500) {
									sqlSession.flushStatements();
									counter = 0;
								}
							}
						}

						sqlSession.flushStatements();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("数据权限设置添加权限异常", e);
		} finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}

	}
}
